<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Role extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'code',
        'description',
        'type',
        'status',
        'sort_order',
        'permissions',
    ];

    protected $casts = [
        'permissions' => 'array',
    ];

    /**
     * 关联用户
     */
    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'user_roles')
            ->withPivot(['start_date', 'end_date', 'status', 'assigned_by', 'assigned_at', 'reason'])
            ->withTimestamps();
    }

    /**
     * 获取当前有效用户
     */
    public function getActiveUsers()
    {
        return $this->users()
            ->wherePivot('status', 'active')
            ->wherePivot('start_date', '<=', now())
            ->where(function ($query) {
                $query->whereNull('end_date')
                    ->orWhere('end_date', '>=', now());
            });
    }

    /**
     * 检查角色是否启用
     */
    public function isActive(): bool
    {
        return $this->status === 'active';
    }

    /**
     * 检查是否为系统角色
     */
    public function isSystem(): bool
    {
        return $this->type === 'system';
    }

    /**
     * 检查是否为自定义角色
     */
    public function isCustom(): bool
    {
        return $this->type === 'custom';
    }

    /**
     * 获取角色类型标签
     */
    public function getTypeLabelAttribute(): string
    {
        $typeLabels = [
            'system' => '系统角色',
            'custom' => '自定义角色',
        ];

        return $typeLabels[$this->type] ?? $this->type;
    }

    /**
     * 获取状态标签
     */
    public function getStatusLabelAttribute(): string
    {
        $statusLabels = [
            'active' => '启用',
            'inactive' => '禁用',
        ];

        return $statusLabels[$this->status] ?? $this->status;
    }

    /**
     * 检查角色是否有指定权限
     */
    public function hasPermission(string $permission): bool
    {
        // 超级管理员拥有所有权限
        if ($this->permissions && in_array('*', $this->permissions)) {
            return true;
        }

        return $this->permissions && in_array($permission, $this->permissions);
    }

    /**
     * 添加权限
     */
    public function addPermission(string $permission): void
    {
        if (!$this->permissions) {
            $this->permissions = [];
        }

        if (!in_array($permission, $this->permissions)) {
            $this->permissions[] = $permission;
        }
    }

    /**
     * 移除权限
     */
    public function removePermission(string $permission): void
    {
        if ($this->permissions) {
            $this->permissions = array_values(array_filter($this->permissions, fn($p) => $p !== $permission));
        }
    }

    /**
     * 设置权限列表
     */
    public function setPermissions(array $permissions): void
    {
        $this->permissions = array_unique($permissions);
    }
}
